﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RWLib
{
    public class ReleaseStatement : StatementBase
    {

        private Formula condition;
        private Fluent effects;

        public Fluent Effects {
            get { return effects; }
        }

        public ReleaseStatement(string _name, Formula _condition, Fluent _effects)
        {
            condition = _condition;
            effects = _effects;
            name = _name;
        }

        public override List<List<Fluent>> Run(List<Fluent> fluents)
        {
            List<List<Fluent>> states = new List<List<Fluent>>();
            bool imp = false;
            if (ImpossibleCondition != null)
            {
                if (ImpossibleCondition.Eval(fluents))
                {
                    imp = true;
                }
            }
            if (condition == null || condition.Eval(fluents) && !imp)
            {
                performed = true;
                var state = fluents.Copy();
                var f = state.Get(effects);
                f.Value = !f.Value.Value;
                f.Changed = true;
                fluents.Get(f.Name).Changed = true;
                states.Add(state);
                states.Add(fluents.Copy());
            }
            else {
                states.Add(fluents.Copy());
                performed = false;
            }
            if (TriggeredBy != null)
            {                
                TriggeredBy.Running = false;
                TriggeredBy = null;
            }
            return states;
        }

        public override bool Conflict(StatementBase action, List<Fluent> state)
        {
            if (action is FluentEffectStatement)
            {
                FluentEffectStatement tmp = action as FluentEffectStatement;

                string nname = this.Effects.Name;
                return tmp.Effects.Fluents.Any(f => nname.Equals(f.Name));
            }
            return false;
        }        

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append(name);
            sb.Append(" releases (");
            sb.Append(effects.ToString());
            sb.Append(")");
            sb.Append(" if (");
            sb.Append(condition.ToString());
            sb.Append(")");
            return sb.ToString();
        }
    }
}
